//
//  AppUtility.m
//  weizhuan
//
//  Created by lixun on 13-8-1.
//  Copyright (c) 2013年 lixun. All rights reserved.
//


#import "AppUtility.h"
#import "MD5Digest.h"
#import "UD.h"
#import "UIConfig.h"
#import "URLConfig.h"
#import "MD5Digest.h"
#include <sys/types.h>

#include <sys/sysctl.h>

NSArray *oldStrArray = nil;
UIWebView *phoneCallWebView;


@implementation AppUtility

#pragma mark -
#pragma mark lifeCycle

static AppUtility *_appUtilityInstance = nil;

+ (AppUtility*)getInstance {
	if (!_appUtilityInstance) {
        _appUtilityInstance = [[AppUtility alloc] init];
        return  _appUtilityInstance;
    }
    return _appUtilityInstance;
}

#pragma mark -
#pragma mark for cache
//for default cache
+ (NSString *)getPathInDefaultDir:(NSString*)inPathName {
	return [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/defaultX/%@",inPathName]];
}

//for download cache
+ (NSString *)getDownloadPathInCache:(NSString*)inName {
	return [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/downloadCache/%@",inName]];
}

+ (BOOL)downloadIsExistInCache:(NSString*)inName {
	NSFileManager *manager = [NSFileManager defaultManager];
	NSString *dir = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/downloadCache"];
	if (![manager fileExistsAtPath:dir]) {
		[manager createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
	}
	NSString *path = [self getDownloadPathInCache:inName];
	return [manager fileExistsAtPath:path];
}

+ (NSString*)getDownloadPathInCacheWithURLStr:(NSString *)inURLStr {
	NSString *path = nil;
	if ((![inURLStr isKindOfClass:[NSString class]]) || ([inURLStr length] == 0)) {
		return nil;
	}
	path = [NSString stringWithFormat:@"%@.amr",[MD5Digest md5:inURLStr]];
	if ([self downloadIsExistInCache:path]) {
		return [self getDownloadPathInCache:path];
	}
	return nil;
}

//for image cache
+ (NSString *)getImagePathInCache:(NSString*)inImageName {
	return [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/imageCache/%@",inImageName]];
}
+(NSString*)getImagePathInCacheWithURLStr:(NSString*)inURLStr{
	if ((![inURLStr isKindOfClass:[NSString class]]) || ([inURLStr length] == 0)) {
		return nil;
	}
	NSString *imageName = [NSString stringWithFormat:@"%@.png",[MD5Digest md5:inURLStr]];
   return [AppUtility getImagePathInCache:imageName];
}

+ (BOOL)imageIsExistInCache:(NSString*)inImageName {
	NSFileManager *manager = [NSFileManager defaultManager];
	NSString *dir = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/imageCache"];
	if (![manager fileExistsAtPath:dir]) {
		[manager createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
	}
	NSString *path = [self getImagePathInCache:inImageName];
	return [manager fileExistsAtPath:path];
}

+ (UIImage*)getImageInCacheWithURLStr:(NSString *)inURLStr {
	UIImage *image = nil;
	NSString *imageName = nil;
	
	if ((![inURLStr isKindOfClass:[NSString class]]) || ([inURLStr length] == 0)) {
		return nil;
	}
	imageName = [NSString stringWithFormat:@"%@.png",[MD5Digest md5:inURLStr]];
	if ([AppUtility imageIsExistInCache:imageName]) {
		image = [UIImage imageWithContentsOfFile:[AppUtility getImagePathInCache:imageName]];
	}
	return image;
}


//for duihua cache
+ (void)createDuiHuaCacheDir {
	NSFileManager *manager = [NSFileManager defaultManager];
	NSString *dir = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/duiHuaCache"];
	if (![manager fileExistsAtPath:dir]) {
		[manager createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
	}
}

+ (NSString *)getFilePathInDuiHuaCache:(NSString*)fileName_ {
	return [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/duiHuaCache/%@",fileName_]];
}

+ (BOOL)fileIsExistInDuiHuaCache:(NSString*)fileName_ {
	NSFileManager *manager = [NSFileManager defaultManager];
	NSString *dir = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/duiHuaCache"];
	if (![manager fileExistsAtPath:dir]) {
		[manager createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
	}
	NSString *path = [self getFilePathInDuiHuaCache:fileName_];
	return [manager fileExistsAtPath:path];
}

#pragma mark -
#pragma mark images
+ (UIImage*)getLocalImage:(NSString*)inImgName {
	NSString *path = [[NSBundle mainBundle] pathForResource:inImgName ofType:@"png"];
	return [UIImage imageWithContentsOfFile:path];
}

+ (UIImage*)getLocalJGPImage:(NSString*)inImgName
{
    
    NSString *path = [[NSBundle mainBundle] pathForResource:inImgName ofType:@"jpg"];
	return [UIImage imageWithContentsOfFile:path];
}


+ (UIImage*)getLocalImageWithCache:(NSString*)inImgName {
	NSString *path = [NSString stringWithFormat:@"%@.png",inImgName];
	return [UIImage imageNamed:path];
}

//+ (NSString*)getNetImagePathWithWidth:(int)width_ andHeight:(int)height_ andSrc:(NSString*)src_ {
//	return [NSString stringWithFormat:@"%@forum.php?mod=image&width=%d&height=%d&src=%@", kMainURL, width_, height_, src_];
//}

+(UIImage *)rotateImage:(UIImage *)aImage {
	CGImageRef imgRef = aImage.CGImage;
	CGFloat width = CGImageGetWidth(imgRef);
	CGFloat height = CGImageGetHeight(imgRef);
	CGAffineTransform transform = CGAffineTransformIdentity;
	CGRect bounds = CGRectMake(0, 0, width, height);
	CGFloat scaleRatio = 1;
	CGFloat boundHeight;
	UIImageOrientation orient = aImage.imageOrientation;
	
	switch(orient) {
		case UIImageOrientationUp: //EXIF = 1
			transform = CGAffineTransformIdentity;
			break;
		case UIImageOrientationUpMirrored: //EXIF = 2
			transform = CGAffineTransformMakeTranslation(width, 0.0);
			transform = CGAffineTransformScale(transform, -1.0, 1.0);
			break;
		case UIImageOrientationDown: //EXIF = 3
			transform = CGAffineTransformMakeTranslation(width, height);
			transform = CGAffineTransformRotate(transform, M_PI);
			break;
		case UIImageOrientationDownMirrored: //EXIF = 4
			transform = CGAffineTransformMakeTranslation(0.0, height);
			transform = CGAffineTransformScale(transform, 1.0, -1.0);
			break;
		case UIImageOrientationLeftMirrored: //EXIF = 5
			boundHeight = bounds.size.height;
			bounds.size.height = bounds.size.width;
			bounds.size.width = boundHeight;
			transform = CGAffineTransformMakeTranslation(height, width);
			transform = CGAffineTransformScale(transform, -1.0, 1.0);
			transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
			break;
		case UIImageOrientationLeft: //EXIF = 6
			boundHeight = bounds.size.height;
			bounds.size.height = bounds.size.width;
			bounds.size.width = boundHeight;
			transform = CGAffineTransformMakeTranslation(0.0, width);
			transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
			break;
		case UIImageOrientationRightMirrored: //EXIF = 7
			boundHeight = bounds.size.height;
			bounds.size.height = bounds.size.width;
			bounds.size.width = boundHeight;
			transform = CGAffineTransformMakeScale(-1.0, 1.0);
			transform = CGAffineTransformRotate(transform, M_PI / 2.0);
			break;
		case UIImageOrientationRight: //EXIF = 8
			boundHeight = bounds.size.height;
			bounds.size.height = bounds.size.width;
			bounds.size.width = boundHeight;
			transform = CGAffineTransformMakeTranslation(height, 0.0);
			transform = CGAffineTransformRotate(transform, M_PI / 2.0);
			break;
		default:
			[NSException raise:NSInternalInconsistencyException format:@"Invalid image orientation"];
	}
	UIGraphicsBeginImageContext(bounds.size);
	CGContextRef context = UIGraphicsGetCurrentContext();
	if (orient == UIImageOrientationRight || orient == UIImageOrientationLeft) {
		CGContextScaleCTM(context, -scaleRatio, scaleRatio);
		CGContextTranslateCTM(context, -height, 0);
	} else {
		CGContextScaleCTM(context, scaleRatio, -scaleRatio);
		CGContextTranslateCTM(context, 0, -height);
	}
	
	CGContextConcatCTM(context, transform);
	CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, width, height), imgRef);
	UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
	return imageCopy;
}

+ (CGSize)sizeFit:(CGSize)originSize toSize:(CGSize)maxSize {
	CGSize newSize;
	if (originSize.width <= maxSize.width) {
		if (originSize.height <= maxSize.height) {
			newSize = originSize;
		}
		else {
			newSize.height = maxSize.height;
			newSize.width = maxSize.height/originSize.height*originSize.width;
		}
	}
	else {
		if (originSize.height <= maxSize.height) {
			newSize.width = maxSize.width;
			newSize.height = maxSize.width/originSize.width*originSize.height;
		}
		else {
			if (originSize.width/maxSize.width >= originSize.height/maxSize.height) {
				newSize.width = maxSize.width;
				newSize.height = maxSize.width/originSize.width*originSize.height;
			}
			else {
				newSize.height = maxSize.height;
				newSize.width = maxSize.height/originSize.height*originSize.width;
			}
		}
	}
	return newSize;
}

+ (UIImage *)resizeImage:(UIImage*)image_ andSize:(CGSize)size_ {	
	UIGraphicsBeginImageContext(size_);  
	[image_ drawInRect:CGRectMake(0, 0, size_.width, size_.height)];  
	UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();  
	UIGraphicsEndImageContext();  
	return scaledImage; 
}

#pragma mark -
#pragma mark date

+ (NSDate *)stringToDate:(NSString *)string {   
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
	[formatter setTimeZone:[NSTimeZone localTimeZone]];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date = [formatter dateFromString:string];
    [formatter release];
    return date;
}

+ (NSString *)dateToString:(NSDate *)date {   
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
	[formatter setTimeZone:[NSTimeZone localTimeZone]];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *string = [formatter stringFromDate:date];
    [formatter release];
    return string;
}
+(NSData *)Image_TransForm_Data:(UIImage *)image
{
    NSData *imageData = UIImageJPEGRepresentation(image , 0.5);
    //几乎是按0.5图片大小就降到原来的一半 比如这里 24KB 降到11KB
    return imageData;
}
+ (void)showNetworkActivityIndicator:(BOOL)inShow {
	[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:inShow];
}

#pragma mark -
#pragma mark timeout
+ (BOOL)checkTimeOutWithStartTime:(NSString*)inStartTime andInterval:(double)inInterval {
    NSDate *curDate = [NSDate date];
    NSDate *startDate = [AppUtility stringToDate:inStartTime];
    double timeDuration =[curDate timeIntervalSinceDate:startDate];
    if (timeDuration>=inInterval) {
		return YES;
    }
	return NO;
}

+ (BOOL)checkTimeOutWithStartTime:(NSString*)inStartTime andNowTime:(NSString*)inNowTime andInterval:(NSTimeInterval)inInterval {
    NSDate *curDate = [AppUtility stringToDate:inNowTime];
    NSDate *startDate = [AppUtility stringToDate:inStartTime];
    NSTimeInterval timeDuration =[curDate timeIntervalSinceDate:startDate];
    if (timeDuration >= inInterval) {
		return YES;
    }
	return NO;
}

#pragma mark -
#pragma mark for device
+ (BOOL)isIPhone4 {
	if ([[[UIDevice currentDevice] systemVersion] floatValue] < 3.2) {
		return NO;
	}
	if ([UIScreen instancesRespondToSelector:@selector(currentMode)]) {
		return CGSizeEqualToSize(CGSizeMake(640, 960), [[UIScreen mainScreen] currentMode].size);
	}
	return NO;
}

#pragma mark -
#pragma mark for custom colors
+ (UIColor*)getViewBGColor {
//	return [UIColor colorWithPatternImage:[AppUtility getLocalImageWithCache:@"bg_main"]];
//	return [UIColor whiteColor];
  return RGBCOLOR(230, 230, 230);
}

+ (UIColor*)getNavBarBGColor {
	return [UIColor colorWithRed:228/255.0 green:33/255.0 blue:50/255.0 alpha:1.0];
}

+ (UIBarButtonItem*)getNavBackBtnItemWith:(SEL)inSelector andTitle:(NSString*)inTitle andTarget:(id)inTarget {
	UIImage *imageNormal = [AppUtility getLocalImageWithCache:@"back_nav"];
	UIImage *imageHover =  [AppUtility getLocalImageWithCache:@"back_nav"];
	UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
	[button setFrame:CGRectMake(0, 0, 8, 17)];

	if (inTitle) {
		[button setBackgroundImage:imageNormal forState:UIControlStateNormal];
		[button setBackgroundImage:imageHover forState:UIControlStateHighlighted];
		[button setTitle:inTitle forState:UIControlStateNormal];
		[button setTitleColor:kNavBtnTextColor forState:UIControlStateNormal];
		[button.titleLabel setFont:[UIFont boldSystemFontOfSize:kNavBtnFontSize]];
	} else {
		[button setImage:imageNormal forState:UIControlStateNormal];
		[button setImage:imageHover forState:UIControlStateHighlighted];
	}
	[button addTarget:inTarget action:inSelector forControlEvents:UIControlEventTouchUpInside];
	
	UIImageView *backImgae = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 25)];
	backImgae.center = button.center;
	backImgae.image = [AppUtility getLocalImageWithCache:@"icon_back"];
	[button addSubview:backImgae];
	[backImgae release];
	
	UIBarButtonItem *back = [[[UIBarButtonItem alloc] initWithCustomView:button] autorelease];
	return back;
}

+ (UIBarButtonItem*)getDrawerNavBtnItemWith:(SEL)inSelector andTitle:(NSString*)inTitle andTarget:(id)inTarget {
	UIImage *imageNormal = [AppUtility getLocalImageWithCache:@"nav_back"];
	UIImage *imageHover = [AppUtility getLocalImageWithCache:@"nav_back_selected"];
	UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
	[button setFrame:CGRectMake(0, 0, 45, 32)];
	
	if (inTitle) {
		[button setBackgroundImage:imageNormal forState:UIControlStateNormal];
		[button setBackgroundImage:imageHover forState:UIControlStateHighlighted];
		[button setTitle:inTitle forState:UIControlStateNormal];
		[button setTitleColor:kNavBtnTextColor forState:UIControlStateNormal];
		[button.titleLabel setFont:[UIFont boldSystemFontOfSize:kNavBtnFontSize]];
	} else {
		[button setImage:imageNormal forState:UIControlStateNormal];
		[button setImage:imageHover forState:UIControlStateHighlighted];
	}
	[button addTarget:inTarget action:inSelector forControlEvents:UIControlEventTouchUpInside];
	UIImageView *backImgae = [[UIImageView alloc] initWithImage:[AppUtility getLocalImageWithCache:@"icon_dt"]];
	backImgae.frame = CGRectMake(0, 0, 30, 25);
	backImgae.center = button.center;
	[button addSubview:backImgae];
	[backImgae release];
	UIBarButtonItem *back = [[[UIBarButtonItem alloc] initWithCustomView:button] autorelease];
	return back;
}

+ (UIBarButtonItem*)getNavBtnItemLefBacktWith:(SEL)inSelector andTarget:(id)inTarget
{
    //94 39  47 20
    	UIImage *imageNormal = [AppUtility getLocalImage:@"Back"];
    //	UIImage *imageHover =  [AppUtility getLocalImageWithCache:@"nav_back_press"];
	UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
	[button setFrame:CGRectMake(0, 0, 48, 42)];
    button.imageEdgeInsets = UIEdgeInsetsMake(11.5, 9, 11.5, 29);
    button.backgroundColor = [UIColor clearColor];
    [button setImage:imageNormal forState:UIControlStateNormal];
    [button addTarget:inTarget action:inSelector forControlEvents:UIControlEventTouchUpInside];
    
	return [[[UIBarButtonItem alloc] initWithCustomView:button] autorelease];
}




+ (UIBarButtonItem*)getNavBtnItemLeftWith:(SEL)inSelector andTitle:(NSString*)inTitle andTarget:(id)inTarget andFont:(int)fontsize {
	UIImage *imageNormal = [AppUtility getLocalImage:@"back_nav"];
//	UIImage *imageHover =  [AppUtility getLocalImageWithCache:@"nav_back_press"];
	UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    //27 58  8 17 40 58
	[button setFrame:CGRectMake(0, 0, 50, 40)];
//    button.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);

    button.backgroundColor = [UIColor clearColor];
	if (inTitle) {
		[button setImage:imageNormal forState:UIControlStateNormal];
        
        button.imageEdgeInsets = UIEdgeInsetsMake(5.5, 0, 5.5, 40);

//		[button setBackgroundImage:imageHover forState:UIControlStateHighlighted];
		[button setTitle:inTitle forState:UIControlStateNormal];
		[button setTitleColor:TITLECOLOR forState:UIControlStateNormal];
        [button setTitleColor:KNavBtnTextPressColor forState:UIControlStateHighlighted];

        button.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0);

		[button.titleLabel setFont:[UIFont boldSystemFontOfSize:fontsize]];
	}
	[button addTarget:inTarget action:inSelector forControlEvents:UIControlEventTouchUpInside];
	return [[[UIBarButtonItem alloc] initWithCustomView:button] autorelease];
}
+ (UIBarButtonItem*)getNavBtnItemLeft1With:(SEL)inSelector andTitle:(NSString*)inTitle andTarget:(id)inTarget andFont:(int)fontsize {
    UIImage *imageNormal = [AppUtility getLocalImage:@"white_back_nav"];
    //	UIImage *imageHover =  [AppUtility getLocalImageWithCache:@"nav_back_press"];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    //27 58  8 17 40 58
    [button setFrame:CGRectMake(0, 0, 50, 40)];
    //    button.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    
    button.backgroundColor = [UIColor clearColor];
    if (inTitle) {
        [button setImage:imageNormal forState:UIControlStateNormal];
        
        button.imageEdgeInsets = UIEdgeInsetsMake(5.5, 0, 5.5, 40);
        
        //		[button setBackgroundImage:imageHover forState:UIControlStateHighlighted];
        [button setTitle:inTitle forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
        
        button.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0);
        
        [button.titleLabel setFont:[UIFont boldSystemFontOfSize:fontsize]];
    }
    [button addTarget:inTarget action:inSelector forControlEvents:UIControlEventTouchUpInside];
    return [[[UIBarButtonItem alloc] initWithCustomView:button] autorelease];
}

+ (UIBarButtonItem*)getNavBtnItemRightWith:(SEL)inSelector andTitle:(NSString*)inTitle andTarget:(id)inTarget andFont:(int)fontsize {
//	UIImage *imageNormal = [AppUtility getLocalImageWithCache:@"nav_right"];
//	UIImage *imageHover =  [AppUtility getLocalImageWithCache:@"nav_right_press"];
	UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
	[button setFrame:CGRectMake(0, 0, 50, 28)];
    button.backgroundColor = [UIColor clearColor];
	if (inTitle) {
//		[button setBackgroundImage:imageNormal forState:UIControlStateNormal];
//		[button setBackgroundImage:imageHover forState:UIControlStateHighlighted];
		[button setTitle:inTitle forState:UIControlStateNormal];
		[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
		[button.titleLabel setFont:[UIFont boldSystemFontOfSize:fontsize]];
        [button setTitleColor:KNavBtnTextPressColor forState:UIControlStateHighlighted];
	}
	[button addTarget:inTarget action:inSelector forControlEvents:UIControlEventTouchUpInside];
	return [[[UIBarButtonItem alloc] initWithCustomView:button] autorelease];
}

//导航左右按钮的 图片大小设置；


+ (UIBarButtonItem*)getNavBtnItemHomePersonWith:(SEL)inSelector andTarget:(id)inTarget
{
    UIImage *imageNormal = [AppUtility getLocalImageWithCache:@"Set@2x"];
    UIImage *imageHover =  [AppUtility getLocalImageWithCache:@"Set@2x"];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setFrame:CGRectMake(0, 0, 40,40)];
    [button setImageEdgeInsets:UIEdgeInsetsMake(10,10,10,10)];
    [button setImage:imageHover forState:UIControlStateHighlighted];
    
    [button setImage:imageNormal forState:UIControlStateNormal];
    
    [button addTarget:inTarget action:inSelector forControlEvents:UIControlEventTouchUpInside];
    return [[[UIBarButtonItem alloc] initWithCustomView:button] autorelease];
}
+ (UIBarButtonItem*)getNavBtnItemHomeLeftWith:(SEL)inSelector andTarget:(id)inTarget
{
    UIImage *imageNormal = [AppUtility getLocalImageWithCache:@"Set@2x"];
    UIImage *imageHover =  [AppUtility getLocalImageWithCache:@"Set@2x"];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setFrame:CGRectMake(0, 0, 45,45)];
    [button setImageEdgeInsets:UIEdgeInsetsMake(12.5,12.5,12.5, 12.5)];

    [button setImage:imageHover forState:UIControlStateHighlighted];
    
    [button setImage:imageNormal forState:UIControlStateNormal];
    
    
    
    [button addTarget:inTarget action:inSelector forControlEvents:UIControlEventTouchUpInside];
    return [[[UIBarButtonItem alloc] initWithCustomView:button] autorelease];
}


+ (UIBarButtonItem*)getNavBtnItemRightWith:(SEL)inSelector andImageName_nomal:(NSString*)imageName_nomal andImageName_selected:(NSString *)imageName_selected andTarget:(id)inTarget andUIEdgeInsets:(UIEdgeInsets)uiEdgeInset andButtonSize:(CGSize)btnSize
{

	UIImage *imageNormal = [AppUtility getLocalImageWithCache:imageName_nomal];
	UIImage *imageHover =  [AppUtility getLocalImageWithCache:imageName_selected];
	UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
	[button setFrame:CGRectMake(0, 0, btnSize.width, btnSize.height)];
    [button setImageEdgeInsets:uiEdgeInset];
	if (imageName_selected) {
		[button setImage:imageHover forState:UIControlStateHighlighted];
	}
    
    if (imageName_nomal) {
		[button setImage:imageNormal forState:UIControlStateNormal];
	}

    
	[button addTarget:inTarget action:inSelector forControlEvents:UIControlEventTouchUpInside];
	return [[[UIBarButtonItem alloc] initWithCustomView:button] autorelease];
}



+ (UIBarButtonItem*)getNavBtnItemLeftWith:(SEL)inSelector andImageName_nomal:(NSString*)imageName_nomal andImageName_selected:(NSString *)imageName_selected andTarget:(id)inTarget andUIEdgeInsets:(UIEdgeInsets )uiEdgeInset andButtonSize:(CGSize)btnSize
{

	UIImage *imageNormal = [AppUtility getLocalImageWithCache:imageName_nomal];
	UIImage *imageHover =  [AppUtility getLocalImageWithCache:imageName_selected];
	UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
	[button setFrame:CGRectMake(0, 0, btnSize.width, btnSize.height)];
    [button setImageEdgeInsets:uiEdgeInset];
	if (imageName_selected) {
		[button setImage:imageHover forState:UIControlStateHighlighted];
	}
    
    if (imageName_nomal) {
		[button setImage:imageNormal forState:UIControlStateNormal];
	}
	[button addTarget:inTarget action:inSelector forControlEvents:UIControlEventTouchUpInside];
	return [[[UIBarButtonItem alloc] initWithCustomView:button] autorelease];
}

//导航左右按钮 的图片文字设置
+ (UIBarButtonItem*)getNavBtnItemRightWith:(SEL)inSelector andImageName_nomal:(NSString*)imageName_nomal andImageName_selected:(NSString *)imageName_selected andTarget:(id)inTarget andImageEdgeInsets:(UIEdgeInsets)imageEdgeInset andWithTitle:(NSString *)title andWithTitleColor:(UIColor *)titleColor andWithTitleFont:(int)titleFont andTitleEdgeInset:(UIEdgeInsets)titleEdgeInset andButtonSize:(CGSize)btnSize
{
    
	UIImage *imageNormal = [AppUtility getLocalImageWithCache:imageName_nomal];
	UIImage *imageHover =  [AppUtility getLocalImageWithCache:imageName_selected];
	UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
	[button setFrame:CGRectMake(0, 0, btnSize.width, btnSize.height)];
    [button setTitle:title forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:titleFont];
    [button setTitleColor:titleColor forState:UIControlStateNormal];
    [button setImageEdgeInsets:imageEdgeInset];
    [button setTitleEdgeInsets:titleEdgeInset];

	if (imageName_selected) {
		[button setImage:imageHover forState:UIControlStateHighlighted];
	}
    
    if (imageName_nomal) {
		[button setImage:imageNormal forState:UIControlStateNormal];
	}
    
	[button addTarget:inTarget action:inSelector forControlEvents:UIControlEventTouchUpInside];
	return [[[UIBarButtonItem alloc] initWithCustomView:button] autorelease];

}


+ (UIBarButtonItem*)getNavBtnItemLeftWith:(SEL)inSelector andImageName_nomal:(NSString*)imageName_nomal andImageName_selected:(NSString *)imageName_selected andTarget:(id)inTarget andImageEdgeInsets:(UIEdgeInsets )imageEdgeInset andWithTitle:(NSString *)title andWithTitleColor:(UIColor *)titleColor andWithTitleFont:(int)titleFont andTitleEdgeInset:(UIEdgeInsets)titleEdgeInset andButtonSize:(CGSize)btnSize
{
	UIImage *imageNormal = [AppUtility getLocalImageWithCache:imageName_nomal];
	UIImage *imageHover =  [AppUtility getLocalImageWithCache:imageName_selected];
	UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
	[button setFrame:CGRectMake(0, 0, btnSize.width, btnSize.height)];
    [button setTitle:title forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:titleFont];
    [button setTitleColor:titleColor forState:UIControlStateNormal];
    [button setImageEdgeInsets:imageEdgeInset];
    [button setTitleEdgeInsets:titleEdgeInset];
    
	if (imageName_selected) {
		[button setImage:imageHover forState:UIControlStateHighlighted];
	}
    if (imageName_nomal) {
		[button setImage:imageNormal forState:UIControlStateNormal];
	}
	[button addTarget:inTarget action:inSelector forControlEvents:UIControlEventTouchUpInside];
	return [[[UIBarButtonItem alloc] initWithCustomView:button] autorelease];

}


/*
+ (UIButton*)getNavBtnLeftWith:(SEL)inSelector andTitle:(NSString*)inTitle andTarget:(id)inTarget {
	UIImage *imageNormal = [AppUtility getLocalImageWithCache:@"btn_nav_left"];
	UIImage *imageHover =  [AppUtility getLocalImageWithCache:@"btn_nav_left_hov"];
	UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
	[button setFrame:CGRectMake(0, 0, 70, 32)];
	if (inTitle) {
		[button setBackgroundImage:imageNormal forState:UIControlStateNormal];
		[button setBackgroundImage:imageHover forState:UIControlStateHighlighted];
		[button setTitle:inTitle forState:UIControlStateNormal];
		[button setTitleColor:kNavBtnTextColor forState:UIControlStateNormal];
		[button.titleLabel setFont:[UIFont boldSystemFontOfSize:kNavBtnFontSize]];
	} else {
		[button setImage:imageNormal forState:UIControlStateNormal];
		[button setImage:imageHover forState:UIControlStateHighlighted];
	}
	[button addTarget:inTarget action:inSelector forControlEvents:UIControlEventTouchUpInside];
	return button;
}

+ (UIButton*)getNavBtnRightWith:(SEL)inSelector andTitle:(NSString*)inTitle andTarget:(id)inTarget {
	UIImage *imageNormal = [AppUtility getLocalImageWithCache:@"btn_nav_right"];
	UIImage *imageHover =  [AppUtility getLocalImageWithCache:@"btn_nav_right_hov"];
	UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
	[button setFrame:CGRectMake(0, 0, 45, 32)];
	if (inTitle) {
		[button setBackgroundImage:imageNormal forState:UIControlStateNormal];
		[button setBackgroundImage:imageHover forState:UIControlStateHighlighted];
		[button setTitle:inTitle forState:UIControlStateNormal];
		[button setTitleColor:kNavBtnTextColor forState:UIControlStateNormal];
		[button.titleLabel setFont:[UIFont boldSystemFontOfSize:kNavBtnFontSize]];
	} else {
		[button setImage:imageNormal forState:UIControlStateNormal];
		[button setImage:imageHover forState:UIControlStateHighlighted];
	}
	[button addTarget:inTarget action:inSelector forControlEvents:UIControlEventTouchUpInside];
	return button;
}
*/
+ (UIBarButtonItem*)getToolBtnItemLeftWith:(SEL)inSelector andTitle:(NSString*)inTitle andTarget:(id)inTarget {
	UIImage *imageNormal = [AppUtility getLocalImageWithCache:@"btn_nav_right"];
	UIImage *imageHover =  [AppUtility getLocalImageWithCache:@"btn_nav_right_hov"];
	UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
	[button setFrame:CGRectMake(0, 0, 45, 32)];
	if (inTitle) {
		[button setBackgroundImage:imageNormal forState:UIControlStateNormal];
		[button setBackgroundImage:imageHover forState:UIControlStateHighlighted];
		[button setTitle:inTitle forState:UIControlStateNormal];
		[button setTitleColor:kNavBtnTextColor forState:UIControlStateNormal];
		[button.titleLabel setFont:[UIFont boldSystemFontOfSize:kNavBtnFontSize]];
	} else {
		[button setImage:imageNormal forState:UIControlStateNormal];
		[button setImage:imageHover forState:UIControlStateHighlighted];
	}
	[button addTarget:inTarget action:inSelector forControlEvents:UIControlEventTouchUpInside];
	return [[[UIBarButtonItem alloc] initWithCustomView:button] autorelease];
}

+ (UIBarButtonItem*)getToolBtnItemRightWith:(SEL)inSelector andTitle:(NSString*)inTitle andTarget:(id)inTarget {
	UIImage *imageNormal = [AppUtility getLocalImageWithCache:@"btn_nav_right"];
	UIImage *imageHover =  [AppUtility getLocalImageWithCache:@"btn_nav_right_hov"];
	UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
	[button setFrame:CGRectMake(0, 0, 45, 32)];
	if (inTitle) {
		[button setBackgroundImage:imageNormal forState:UIControlStateNormal];
		[button setBackgroundImage:imageHover forState:UIControlStateHighlighted];
		[button setTitle:inTitle forState:UIControlStateNormal];
		[button setTitleColor:kNavBtnTextColor forState:UIControlStateNormal];
		[button.titleLabel setFont:[UIFont boldSystemFontOfSize:kNavBtnFontSize]];
	} else {
		[button setImage:imageNormal forState:UIControlStateNormal];
		[button setImage:imageHover forState:UIControlStateHighlighted];
	}
	[button addTarget:inTarget action:inSelector forControlEvents:UIControlEventTouchUpInside];
	return [[[UIBarButtonItem alloc] initWithCustomView:button] autorelease];
}

+ (UIBarButtonItem*)getNavBtnItemWith:(SEL)inSelector andNormalImgPath:(NSString*)inNormal andHovImgPath:(NSString*)inHov andTarget:(id)inTarget {
	UIImage *imageNormal = [AppUtility getLocalImageWithCache:inNormal];
	UIImage *imageHover =  [AppUtility getLocalImageWithCache:inHov];
	UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
	[button setFrame:CGRectMake(0, 0, 55, 32)];
    [button setImage:imageNormal forState:UIControlStateNormal];
    [button setImage:imageHover forState:UIControlStateHighlighted];
	[button addTarget:inTarget action:inSelector forControlEvents:UIControlEventTouchUpInside];
	return [[[UIBarButtonItem alloc] initWithCustomView:button] autorelease];
}
#pragma mark for rand num
+ (int)getRand {
	srand((unsigned)time(NULL));
	return rand();
}

#pragma mark for check NSNull
+ (BOOL)isNotNSNull:(id)value_ {
	if (!value_) {
		return NO;
	}
    return (value_ != [NSNull null]);
}

+(NSString*)encryptRC4:(NSString*)input_ key:(NSString*)key_
{
	
    NSMutableArray *iS = [[NSMutableArray alloc] initWithCapacity:256];
    NSMutableArray *iK = [[NSMutableArray alloc] initWithCapacity:256];
	
    for (int i= 0; i<256; i++) {
        [iS addObject:[NSNumber numberWithInt:i]];
    }
	
    int j=1;
	
    for (short i=0; i<256; i++) {
		
        UniChar c = [key_ characterAtIndex:i%key_.length];
		
        [iK addObject:[NSNumber numberWithChar:c]];
    }
	
    j=0;
	
    for (int i=0; i<255; i++) {
        int is = [[iS objectAtIndex:i] intValue];
        UniChar ik = (UniChar)[[iK objectAtIndex:i] charValue];
		
        j = (j + is + ik)%256;
        NSNumber *temp = [iS objectAtIndex:i];
        [iS replaceObjectAtIndex:i withObject:[iS objectAtIndex:j]];
        [iS replaceObjectAtIndex:j withObject:temp];
		
    }
	
    int i=0;
    j=0;
	
    NSString *result = input_;
	
    for (short x=0; x<[input_ length]; x++) {
        i = (i+1)%256;
		
        int is = [[iS objectAtIndex:i] intValue];
        j = (j+is)%256;
		
        int is_i = [[iS objectAtIndex:i] intValue];
        int is_j = [[iS objectAtIndex:j] intValue]; 
		
        int t = (is_i+is_j) % 256;
        int iY = [[iS objectAtIndex:t] intValue];
		
        UniChar ch = (UniChar)[input_ characterAtIndex:x];
        UniChar ch_y = ch^iY;
		
        result = [result stringByReplacingCharactersInRange:NSMakeRange(x, 1) withString:[NSString stringWithCharacters:&ch_y length:1]];
    }
	
    [iS release];
    [iK release];
	
    return result;
}
+(float)screenHeight{
    return [UIScreen mainScreen].bounds.size.height;
//    return [UIScreen mainScreen].applicationFrame.size.height;
}
+(float)screenWidth{
    return [UIScreen mainScreen].bounds.size.width;
}
+(BOOL)isPhone
{
    return (UIUserInterfaceIdiomPhone == [[UIDevice currentDevice] userInterfaceIdiom]);
}
+(NSString *)dayDayWordToString:(NSTimeInterval )interval {
    NSDate *date =[NSDate dateWithTimeIntervalSince1970:interval];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
	[formatter setTimeZone:[NSTimeZone localTimeZone]];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *string = [formatter stringFromDate:date];
    [formatter release];
    return string;
}

+ (NSString *) compareCurrentTime:(NSString *)str
{
    
    //把字符串转为NSdate
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy/MM/dd HH:mm"];
    NSDate *timeDate = [dateFormatter dateFromString:str];
    
    //得到与当前时间差
    NSTimeInterval  timeInterval = [timeDate timeIntervalSinceNow];
    timeInterval = -timeInterval;
    //标准时间和北京时间差8个小时
//    timeInterval = timeInterval - 8*60*60;
    
    long temp = 0;
    NSString *result;
    if (timeInterval/60 < 1) {
        result = [NSString stringWithFormat:@"刚刚"];
    }
    else if((temp = timeInterval/60) <60){
        result = [NSString stringWithFormat:@"%ld分钟前",temp];
    }
    
    else if((temp = temp/60) <24){
        result = [NSString stringWithFormat:@"%ld小时前",temp];
    }
    
    else if((temp = temp/24) <30){
        result = str;
    }
    
    else if((temp = temp/30) <12){
        result = str;
    }
    else{
        temp = temp/12;
        result = str;
    }
    
    return  result;
}


//获得设备型号

+ (NSString *)getCurrentDeviceModel

{
    
    int mib [2];
    
    size_t len;
    
    char *machine;
    
    mib[0] = CTL_HW;
    
    mib[1] = HW_MACHINE;
    
    sysctl(mib, 2, NULL, &len, NULL, 0);
    
    machine = malloc(len);
    
    sysctl(mib, 2, machine, &len, NULL, 0);
    
    NSString *platform = [NSString stringWithCString:machine encoding:NSASCIIStringEncoding];
    
    free(machine);
    
    // iPhone
    
    if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone2G";
    
    if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone3G";
    
    if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone3GS";
    
    if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone4";
    
    if ([platform isEqualToString:@"iPhone3,2"]) return @"iPhone4";
    
    if ([platform isEqualToString:@"iPhone3,3"]) return @"iPhone4";
    
    if ([platform isEqualToString:@"iPhone4,1"]) return @"iPhone4S";
    
    if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone5";
    
    if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone5";
    
    if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone5c";
    
    if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone5c";
    
    if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone5s";
    
    if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone5s";
    
    if ([platform isEqualToString:@"iPhone7,2"]) return @"iPhone6";
    
    if ([platform isEqualToString:@"iPhone7,1"]) return @"iPhone6Plus";
    
    if ([platform isEqualToString:@"iPhone8,1"]) return @"iPhone6s";
    
    if ([platform isEqualToString:@"iPhone8,2"]) return @"iPhone6sPlus";
    
    if ([platform isEqualToString:@"iPhone8,3"]) return @"iPhoneSE";
    
    if ([platform isEqualToString:@"iPhone8,4"]) return @"iPhoneSE";
    
    if ([platform isEqualToString:@"iPhone9,1"]) return @"iPhone7";
    
    if ([platform isEqualToString:@"iPhone9,2"]) return @"iPhone7Plus";
    
    //iPod Touch
    
    if ([platform isEqualToString:@"iPod1,1"])  return @"iPodTouch";
    
    if ([platform isEqualToString:@"iPod2,1"])  return @"iPodTouch2G";
    
    if ([platform isEqualToString:@"iPod3,1"])  return @"iPodTouch3G";
    
    if ([platform isEqualToString:@"iPod4,1"])  return @"iPodTouch4G";
    
    if ([platform isEqualToString:@"iPod5,1"])  return @"iPodTouch5G";
    
    if ([platform isEqualToString:@"iPod7,1"])  return @"iPodTouch6G";
    
    //iPad
    
    if ([platform isEqualToString:@"iPad1,1"])  return @"iPad";
    
    if ([platform isEqualToString:@"iPad2,1"])  return @"iPad2";
    
    if ([platform isEqualToString:@"iPad2,2"])  return @"iPad2";
    
    if ([platform isEqualToString:@"iPad2,3"])  return @"iPad2";
    
    if ([platform isEqualToString:@"iPad2,4"])  return @"iPad2";
    
    if ([platform isEqualToString:@"iPad3,1"])  return @"iPad3";
    
    if ([platform isEqualToString:@"iPad3,2"])  return @"iPad3";
    
    if ([platform isEqualToString:@"iPad3,3"])  return @"iPad3";
    
    if ([platform isEqualToString:@"iPad3,4"])  return @"iPad4";
    
    if ([platform isEqualToString:@"iPad3,5"])  return @"iPad4";
    
    if ([platform isEqualToString:@"iPad3,6"])  return @"iPad4";
    
    //iPad Air
    
    if ([platform isEqualToString:@"iPad4,1"])  return @"iPadAir";
    
    if ([platform isEqualToString:@"iPad4,2"])  return @"iPadAir";
    
    if ([platform isEqualToString:@"iPad4,3"])  return @"iPadAir";
    
    if ([platform isEqualToString:@"iPad5,3"])  return @"iPadAir2";
    
    if ([platform isEqualToString:@"iPad5,4"])  return @"iPadAir2";
    
    //iPad mini
    
    if ([platform isEqualToString:@"iPad2,5"])  return @"iPadmini1G";
    
    if ([platform isEqualToString:@"iPad2,6"])  return @"iPadmini1G";
    
    if ([platform isEqualToString:@"iPad2,7"])  return @"iPadmini1G";
    
    if ([platform isEqualToString:@"iPad4,4"])  return @"iPadmini2";
    
    if ([platform isEqualToString:@"iPad4,5"])  return @"iPadmini2";
    
    if ([platform isEqualToString:@"iPad4,6"])  return @"iPadmini2";
    
    if ([platform isEqualToString:@"iPad4,7"])  return @"iPadmini3";
    
    if ([platform isEqualToString:@"iPad4,8"])  return @"iPadmini3";
    
    if ([platform isEqualToString:@"iPad4,9"])  return @"iPadmini3";
    
    if ([platform isEqualToString:@"iPad5,1"])  return @"iPadmini4";
    
    if ([platform isEqualToString:@"iPad5,2"])  return @"iPadmini4";
    
    if ([platform isEqualToString:@"i386"])      return @"iPhoneSimulator";
    
    if ([platform isEqualToString:@"x86_64"])    return @"iPhoneSimulator";
    
    return platform;
    
}
+(BOOL)judgePassWordLegal:(NSString *)pass{
    BOOL result = false;
    if ([pass length] >= 6&&[pass length] <= 32){
        // 判断长度大于6位后再接着判断是否同时包含数字和字符
        NSString * regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$";
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
        result = [pred evaluateWithObject:pass];
    }
    return result;
}
+(BOOL)judgePassWordLegal1:(NSString *)pass{
    BOOL result = false;
    if ([pass length] >= 8&&[pass length] <= 20){
        // 判断长度大于6位后再接着判断是否同时包含数字和字符
        NSString * regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$";
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
        result = [pred evaluateWithObject:pass];
    }
    return result;
}

+(NSString *)dayDayTimeWordToString:(NSTimeInterval )interval {
    NSDate *date =[NSDate dateWithTimeIntervalSince1970:interval];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setTimeZone:[NSTimeZone localTimeZone]];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSString *string = [formatter stringFromDate:date];
    [formatter release];
    return string;
}


+(NSString *)dayHourWordToString:(NSTimeInterval )interval {
    NSDate *date =[NSDate dateWithTimeIntervalSince1970:interval];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
	[formatter setTimeZone:[NSTimeZone localTimeZone]];
    [formatter setDateFormat:@"MM-dd HH:mm"];
    NSString *string = [formatter stringFromDate:date];
    [formatter release];
    return string;
}
+(NSString *)dayHourWordToString1:(NSTimeInterval )interval {
    NSDate *date =[NSDate dateWithTimeIntervalSince1970:interval];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setTimeZone:[NSTimeZone localTimeZone]];
    [formatter setDateFormat:@"MM月dd日 HH:mm"];
    NSString *string = [formatter stringFromDate:date];
    [formatter release];
    return string;
}
+(NSString *)DelTimedayDayWordToString:(NSTimeInterval )interval {
    NSDate *date =[NSDate dateWithTimeIntervalSince1970:interval];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
	[formatter setTimeZone:[NSTimeZone localTimeZone]];
    [formatter setDateFormat:@"yyyy年MM月dd日"];
    NSString *string = [formatter stringFromDate:date];
    [formatter release];
    return string;
}

+(NSString *)MonthAndDayWordToString:(NSTimeInterval )interval {
    NSDate *date =[NSDate dateWithTimeIntervalSince1970:interval];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
	[formatter setTimeZone:[NSTimeZone localTimeZone]];
    [formatter setDateFormat:@"MM月dd日"];
    NSString *string = [formatter stringFromDate:date];
    [formatter release];
    return string;
}

+(NSString *)OtherMonthAndDayWordToString:(NSTimeInterval )interval {
    NSDate *date =[NSDate dateWithTimeIntervalSince1970:interval];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setTimeZone:[NSTimeZone localTimeZone]];
    [formatter setDateFormat:@"MM-dd"];
    NSString *string = [formatter stringFromDate:date];
    [formatter release];
    return string;
}
+(NSString *)AnotherMonthAndDayWordToString:(NSTimeInterval )interval {
    NSDate *date =[NSDate dateWithTimeIntervalSince1970:interval];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setTimeZone:[NSTimeZone localTimeZone]];
    [formatter setDateFormat:@"MM/dd HH:mm"];
    NSString *string = [formatter stringFromDate:date];
    [formatter release];
    return string;
}
+(NSString *)getTimeFrom:(NSTimeInterval)interval
{
    int fen = (((int)interval%(3600*24))%3600)/60;
    int miao = (((int)interval%(3600*24))%3600)%60;


    return [NSString stringWithFormat:@"%@:%@",fen<10?[NSString stringWithFormat:@"0%d",fen]:[NSString stringWithFormat:@"%d",fen],miao<10?[NSString stringWithFormat:@"0%d",miao]:[NSString stringWithFormat:@"%d",miao]];
}

+(NSString *)getXiTongYear
{
    NSDate *  senddate=[NSDate date];
    NSCalendar  * cal=[NSCalendar  currentCalendar];
    NSUInteger  unitFlags=NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit;
    NSDateComponents * conponent= [cal components:unitFlags fromDate:senddate];
    
    NSInteger year=[conponent year];
    
    NSString *str = [NSString stringWithFormat:@"%ld",(long)year];
    return str;


}
+(NSString *)getXiTongMonth
{
    NSDate *  senddate=[NSDate date];
    NSCalendar  * cal=[NSCalendar  currentCalendar];
    NSUInteger  unitFlags=NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit;
    NSDateComponents * conponent= [cal components:unitFlags fromDate:senddate];
    
    NSInteger year=[conponent month];
    
    NSString *str = [NSString stringWithFormat:@"%ld",(long)year];
    return str;

}
+(NSString *)getXiTongDay
{
    NSDate *  senddate=[NSDate date];
    NSCalendar  * cal=[NSCalendar  currentCalendar];
    NSUInteger  unitFlags=NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit;
    NSDateComponents * conponent= [cal components:unitFlags fromDate:senddate];
    
    NSInteger year=[conponent day];
    
    NSString *str = [NSString stringWithFormat:@"%ld",(long)year];
    return str;

}
+(NSString *)getYearFromTimeInterval:(NSTimeInterval)interval
{
    NSDate *date =[NSDate dateWithTimeIntervalSince1970:interval];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setTimeZone:[NSTimeZone localTimeZone]];
    [formatter setDateFormat:@"yyyy"];
    NSString *string = [formatter stringFromDate:date];
    [formatter release];
    return string;

}
+(NSString *)getMonthFromTimeInterval:(NSTimeInterval)interval
{
    NSDate *date =[NSDate dateWithTimeIntervalSince1970:interval];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setTimeZone:[NSTimeZone localTimeZone]];
    [formatter setDateFormat:@"MM"];
    NSString *string = [formatter stringFromDate:date];
    [formatter release];
    return string;

}
+(NSString *)getDayFromTimeInterval:(NSTimeInterval)interval
{
    NSDate *date =[NSDate dateWithTimeIntervalSince1970:interval];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setTimeZone:[NSTimeZone localTimeZone]];
    [formatter setDateFormat:@"dd"];
    NSString *string = [formatter stringFromDate:date];
    [formatter release];
    return string;

}

+(NSString *)getYearFromData:(NSDate*)date
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setTimeZone:[NSTimeZone localTimeZone]];
    [formatter setDateFormat:@"yyyy"];
    NSString *string = [formatter stringFromDate:date];
    [formatter release];
    return string;

}
+(NSString *)getMonthFromData:(NSDate*)date
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setTimeZone:[NSTimeZone localTimeZone]];
    [formatter setDateFormat:@"MM"];
    NSString *string = [formatter stringFromDate:date];
    [formatter release];
    return string;

}
+(NSString *)getDayFromData:(NSDate*)date
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setTimeZone:[NSTimeZone localTimeZone]];
    [formatter setDateFormat:@"dd"];
    NSString *string = [formatter stringFromDate:date];
    [formatter release];
    return string;
}


+(NSString *)getYearAndMonthAndDay
{
    //获得系统日期 格式 年月日
    NSDate *  senddate=[NSDate date];
    NSCalendar  * cal=[NSCalendar  currentCalendar];
    NSUInteger  unitFlags=NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit;
    NSDateComponents * conponent= [cal components:unitFlags fromDate:senddate];
    
    NSInteger year=[conponent year];
    NSInteger month=[conponent month];
    NSInteger day=[conponent day];
    
    NSString *str = [NSString stringWithFormat:@"%4d年%2d月%2d日",year,month,day];
    return str;
}


+(BOOL)isIOS7{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
        return YES;
    }
    return NO;
}

+(BOOL)isIOS8{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8) {
        return YES;
    }
    return NO;
}
+(BOOL)isIOS9{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9) {
        return YES;
    }
    return NO;
}
+(BOOL)isIOS10{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10) {
        return YES;
    }
    return NO;
}
+(NSString *)getWeekDay
{
    NSString *str = @"";
    NSDate *date = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *comps;
    comps = [calendar components:(NSWeekCalendarUnit | NSWeekdayCalendarUnit | NSWeekdayOrdinalCalendarUnit)   fromDate:date];
    
    switch ([comps weekday]) {
        case 1:
            str = @"星期日";
            break;
        case 2:
            str = @"星期一";
            break;
        case 3:
            str = @"星期二";
            break;
        case 4:
            str = @"星期三";
            break;
        case 5:
            str = @"星期四";
            break;
        case 6:
            str = @"星期五";
            break;
        case 7:
            str = @"星期六";
            break;
        default:
            break;
    }
             return str;
    
}

+(NSString *)getWeekDayFromTime:(NSTimeInterval )interval
{
    NSString *str = @"";
    NSDate *date =[NSDate dateWithTimeIntervalSince1970:interval];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *comps;
    comps = [calendar components:(NSWeekCalendarUnit | NSWeekdayCalendarUnit | NSWeekdayOrdinalCalendarUnit)   fromDate:date];
    
    switch ([comps weekday]) {
        case 1:
            str = @"周日";
            break;
        case 2:
            str = @"周一";
            break;
        case 3:
            str = @"周二";
            break;
        case 4:
            str = @"周三";
            break;
        case 5:
            str = @"周四";
            break;
        case 6:
            str = @"周五";
            break;
        case 7:
            str = @"周六";
            break;
        default:
            break;
    }
    return str;
}

+(NSString *)getMonthAndDay
{
    //获得系统日期
    NSDate *  senddate=[NSDate date];
    NSCalendar  * cal=[NSCalendar  currentCalendar];
    NSUInteger  unitFlags=NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit;
    NSDateComponents * conponent= [cal components:unitFlags fromDate:senddate];
    
    NSInteger month=[conponent month];
    NSInteger day=[conponent day];
    
    NSString *str = [NSString stringWithFormat:@"%2d月%2d日",month,day];
    return str;
}

+(NSString *)getNowDate
{
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970]*1000;
    NSString *timeString = [NSString stringWithFormat:@"%f", a];
    return timeString;
}

+ (BOOL)checkTel:(NSString *)str

{
    
    if ([str length] == 0) {
        
        
        UIAlertView *alert= [[UIAlertView alloc]initWithTitle:@"提示" message:@"手机号格式不正确" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        
        

        [alert show];
        
    
        [alert release];
        
        return NO;
        
    }
    
    NSString *regex = @"^(1[3,4,5,7,8][0-9])\\d{8}";
    
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    
    BOOL isMatch = [pred evaluateWithObject:str];
    
    if (!isMatch) {
        
        UIAlertView *alert= [[UIAlertView alloc]initWithTitle:@"提示" message:@"手机号格式不正确" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        
        [alert show];
        [alert release];
        
        return NO;
    }
    return YES;
    
}

+(void)tellPhone:(NSString *)phone;
{
    
    NSURL *phoneURL = [NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",phone]];
    
    if (!phoneCallWebView ) {
        
        phoneCallWebView = [[UIWebView alloc] initWithFrame:CGRectZero];
        // 这个webView只是一个后台的容易 不需要add到页面上来  效果跟方法二一样 但是这个方法是合法的
        
    }
    
    [phoneCallWebView loadRequest:[NSURLRequest requestWithURL:phoneURL]];
    
}


+(float)widthWithString:(NSString *)string WithFont:(int)font
{
    float width = [string  sizeWithFont:[UIFont systemFontOfSize:font]].width;
    return width;
}

+(float)heightForString:(NSString *)value fontSize:(float)fontSize andWidth:(float)width
{
    CGSize sizeToFit = [value sizeWithFont:[UIFont systemFontOfSize:fontSize] constrainedToSize:CGSizeMake(width, CGFLOAT_MAX) lineBreakMode:NSLineBreakByWordWrapping];
    
    return sizeToFit.height;
}

+(NSString *)distanceBetweenOrderBylat1:(double)lat1 lat2:(double)lat2 lng1:(double)lng1 lng2:(double)lng2

{

    return @"0";
}


+(NSString *)getAppScheme
{
    NSString *appScheme = nil;
	NSArray *scharray = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleURLTypes"];
	if ([scharray count]>0) {
		NSDictionary *subDict = [scharray objectAtIndex:0];
		if ([subDict count]>0) {
			NSArray *urlArray = [subDict objectForKey:@"CFBundleURLSchemes"];
			if ([urlArray count]>0) {
				appScheme = [urlArray objectAtIndex:0];
			}
		}
	}

    return appScheme;
}

+(NSString *)getSecretKeyWithAction:(NSString *)action WithUID:(NSString *)UID
{
    
    NSTimeInterval timeInt =[[NSDate date]timeIntervalSince1970];
    NSString *scrert = [NSString stringWithFormat:@"secretkey=%@&timestamp=%.0f",[MD5Digest md5:[NSString stringWithFormat:@"%.0f%@%@%@",timeInt,PRE_KEY,action,UID]],timeInt];
   return  scrert;
    
}


+(NSString *)getReleaseTime:(int)timeData
{
    int ddd = [[NSDate date] timeIntervalSince1970]-timeData;
    
    int day = ddd/(3600*24);
    int hour = (ddd%(3600*24))/3600;
    int fen = ((ddd%(3600*24))%3600)/60;
    
    if (day>0) {
        
        return [NSString stringWithFormat:@"%d天前",day];

    }
    else
    {
        if (hour>0) {
            
            return [NSString stringWithFormat:@"%d小时前",hour];

        }
        else
        {
            return [NSString stringWithFormat:@"%d分钟前",fen];

        }
    }
    
}


+ (BOOL)isBlankString:(NSString *)string{
    
    if (string == nil) {
        
        return YES;
        
    }
    
    if (string == NULL) {
        
        return YES;
        
    }
    
    if ([string isKindOfClass:[NSNull class]]) {
        
        return YES;
        
    }
    
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0) {
        
        return YES;
        
    } 
    
    return NO;
    
}

+ (BOOL)isContainsEmoji:(NSString *)string {
    __block BOOL isEomji = NO;
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:
     ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
         const unichar hs = [substring characterAtIndex:0];
         if (0xd800 <= hs && hs <= 0xdbff) {
             if (substring.length > 1) {
                 const unichar ls = [substring characterAtIndex:1];
                 const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                 if (0x1d000 <= uc && uc <= 0x1f77f) {
                     isEomji = YES;
                 }
             }
         } else if (substring.length > 1) {
             const unichar ls = [substring characterAtIndex:1];
             if (ls == 0x20e3) {
                 isEomji = YES;
             }
         } else {
             if (0x2100 <= hs && hs <= 0x27ff && hs != 0x263b) {
                 isEomji = YES;
             } else if (0x2B05 <= hs && hs <= 0x2b07) {
                 isEomji = YES;
             } else if (0x2934 <= hs && hs <= 0x2935) {
                 isEomji = YES;
             } else if (0x3297 <= hs && hs <= 0x3299) {
                 isEomji = YES;
             } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50|| hs == 0x231a ) {
                 isEomji = YES;
             }
         }
     }];
    return isEomji;
}


+(NSString *)noBlankMyDic:(NSMutableDictionary *)myDic theKey:(NSString *)key
{
    if ([AppUtility isBlankString:[myDic objectForKey:key]]) {
        
        return @"";
        
    }
    else
    {
        return [myDic objectForKey:key];
    }
}

+ (BOOL)validateIDCardNumber:(NSString *)value {
    
    value = [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    
    
   long int length =0;
    
    if (!value) {
        
        return NO;
        
    }else {
        
        length = [value length];
        
        
        
        if (length !=15 && length !=18) {
            
            return NO;
            
        }
        
    }
    
    // 省份代码
    
    NSArray *areasArray =@[@"11",@"12", @"13",@"14", @"15",@"21", @"22",@"23", @"31",@"32", @"33",@"34", @"35",@"36", @"37",@"41", @"42",@"43", @"44",@"45", @"46",@"50", @"51",@"52", @"53",@"54", @"61",@"62", @"63",@"64", @"65",@"71", @"81",@"82", @"91"];
    
    
    
    NSString *valueStart2 = [value substringToIndex:2];
    
    BOOL areaFlag =NO;
    
    for (NSString *areaCode in areasArray) {
        
        if ([areaCode isEqualToString:valueStart2]) {
            
            areaFlag =YES;
            
            break;
            
        }
        
    }
    
    
    
    if (!areaFlag) {
        
        return false;
        
    }
    
    
    
    
    
    NSRegularExpression *regularExpression;
    
    NSUInteger numberofMatch;
    
    
    
    int year =0;
    
    switch (length) {
            
        case 15:
            
            year = [value substringWithRange:NSMakeRange(6,2)].intValue +1900;
            
            
            
            if (year %4 ==0 || (year %100 ==0 && year %4 ==0)) {
                
                
                
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$"
                                     
                                                                       options:NSRegularExpressionCaseInsensitive
                                     
                                                                         error:nil];//测试出生日期的合法性
                
            }else {
                
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$"
                                     
                                                                       options:NSRegularExpressionCaseInsensitive
                                     
                                                                         error:nil];//测试出生日期的合法性
                
            }
            
            numberofMatch = [regularExpression numberOfMatchesInString:value
                             
                                                              options:NSMatchingReportProgress
                             
                                                                range:NSMakeRange(0, value.length)];
            
            
            
            [regularExpression release];
            
            
            
            if(numberofMatch >0) {
                
                return YES;
                
            }else {
                
                return NO;
                
            }
            
        case 18:
            
            
            year = [value substringWithRange:NSMakeRange(6,4)].intValue;
            
            if (year %4 ==0 || (year %100 ==0 && year %4 ==0)) {
                
                
                
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$"
                                     
                                                                       options:NSRegularExpressionCaseInsensitive
                                     
                                                                         error:nil];//测试出生日期的合法性
                
            }else {
                
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$"
                                     
                                                                       options:NSRegularExpressionCaseInsensitive
                                     
                                                                         error:nil];//测试出生日期的合法性
                
            }
            
            numberofMatch = [regularExpression numberOfMatchesInString:value
                             
                                                              options:NSMatchingReportProgress
                             
                                                                range:NSMakeRange(0, value.length)];
            
            
            
            [regularExpression release];
            
            
            
            if(numberofMatch >0) {
                
                int S = ([value substringWithRange:NSMakeRange(0,1)].intValue + [value substringWithRange:NSMakeRange(10,1)].intValue) *7 + ([value substringWithRange:NSMakeRange(1,1)].intValue + [value substringWithRange:NSMakeRange(11,1)].intValue) *9 + ([value substringWithRange:NSMakeRange(2,1)].intValue + [value substringWithRange:NSMakeRange(12,1)].intValue) *10 + ([value substringWithRange:NSMakeRange(3,1)].intValue + [value substringWithRange:NSMakeRange(13,1)].intValue) *5 + ([value substringWithRange:NSMakeRange(4,1)].intValue + [value substringWithRange:NSMakeRange(14,1)].intValue) *8 + ([value substringWithRange:NSMakeRange(5,1)].intValue + [value substringWithRange:NSMakeRange(15,1)].intValue) *4 + ([value substringWithRange:NSMakeRange(6,1)].intValue + [value substringWithRange:NSMakeRange(16,1)].intValue) *2 + [value substringWithRange:NSMakeRange(7,1)].intValue *1 + [value substringWithRange:NSMakeRange(8,1)].intValue *6 + [value substringWithRange:NSMakeRange(9,1)].intValue *3;
                
                int Y = S %11;
                
                NSString *M =@"F";
                
                NSString *JYM =@"10X98765432";
                
                M = [JYM substringWithRange:NSMakeRange(Y,1)];// 判断校验位
                
                if ([M isEqualToString:[value substringWithRange:NSMakeRange(17,1)]]) {
                    
                    return YES;// 检测ID的校验位
                    
                }else {
                    
                    return NO;
                    
                }
                
                
            }else {
                
                return NO;
                
            }
            
        default:
            
            return false;
            
    }
    
}


//判断邮箱格式
+(BOOL)isValidateEmail:(NSString *)email

{
    
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES%@",emailRegex];
    
    return [emailTest evaluateWithObject:email];
    
}

+ (BOOL)validateNumber:(NSString*)number
{
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length)
    {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0)
        {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}

+(void)reSetViewFrame:(UIView *)view
{
    
    view.frame = CGRectMake1(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, view.frame.size.height);
    
}

@end
